# xml文件转成pdf文件脚本
# *--Author 王帅

import datetime
import hashlib
import time
import docx, os
import pymysql
import pythoncom
import xmltodict
from win32com.client import DispatchEx

online_db = pymysql.connect(host="121.4.69.146", user='root', password='xhhg@2020', port=3306, db="big_data",
                            use_unicode=True, charset='utf8')
cursor = online_db.cursor()


def create_doc(item, save_name):
    """制作撤回声明"""
    # 创建文档对象,获得word文档
    path = r'model_file/hz_temp.docx'
    document = docx.Document(path)
    run = document.paragraphs[2].add_run(item['ajbh'])
    run = document.paragraphs[3].add_run(item['sqh'])
    run = document.paragraphs[4].add_run(item['name'])
    run = document.paragraphs[5].add_run(item['tjr'])
    run = document.paragraphs[6].add_run(item['sdsj'])
    run = document.paragraphs[8].add_run(item['sdwj'])
    save_file_path = os.path.join(os.getcwd(), 'example_modified.docx')
    document.save(save_file_path)
    docx_to_pdf(save_file_path, save_name)  # pdf_path  pdf路径


def docx_to_pdf(save_file_path, save_name):
        word = DispatchEx('kwps.Application')
        doc = word.Documents.Open(save_file_path)
        doc.SaveAs(save_name, FileFormat=17)
        doc.Close()
        word.Quit()


def xml_2_pdf(xml_file):
    # 读取XML文件
    with open(xml_file, 'r', encoding='utf-8') as f:
        xml_data = f.read()
    # 将XML转换为Python字典
    data_dict = xmltodict.parse(xml_data)
    item = {"ajbh": data_dict['data-bus']['ANJIANBH'], 'sqh': data_dict['data-bus']['SHENQINGH'],
            'name': data_dict['data-bus']['FAMINGCZMC'],
            "tjr": data_dict['data-bus']['XINGMINGHMC'], 'sdsj': data_dict['data-bus']['SHOUDAOSJ'],
            'sdwj': data_dict['data-bus']['SHOUDAOWJ']['WENJIANLB']['WENJIANDX'],
            'hzsj': data_dict['data-bus']['HUIZHIFSSJ']}
    return item


def get_sqr(item):
    sql = f"SELECT patent_user FROM `big_data`.`xhhg_pantent_status` WHERE `application_number` = 'ZL{item['sqh']}'"
    cursor.execute(sql)
    data = cursor.fetchall()
    try:
        item['sqr'] = data[0][0]
    except:
        item['sqr'] = '手动查询'
    return item


def MainFunc(file_path, xml_path):
    print(file_path)
    if os.path.isfile(xml_path):
        # path = r'D:\工作文件\桌面文件\工作用文件\自动化\CPC纯代码下载文件\22222222\PDF\电子回执\2023-06-12_202211586241X_一种康复用按摩装置_电子申请回执_XHHG.pdf'

        item = xml_2_pdf(xml_path)
        item = get_sqr(item)
        create_doc(item, file_path)


